<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意:只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
      >
      </el-alert>
    </el-card>
    <p>
      请选择商品分类：
      <el-cascader
        v-model="selectedKeys"
        :options="cateList"
        clearable
        :props="{
          expandTrigger: 'hover',
          label: 'cat_name',
          value: 'cat_id',
        }"
        @change="handleCascaderChange"
      ></el-cascader>
    </p>
    <el-tabs v-model="activeName" @tab-click="handleCascaderChange">
      <el-tab-pane label="动态参数" name="many"
        ><el-button
          type="primary"
          size="mini"
          :disabled="isBtnDisabled"
          @click="showAddDialog"
          >添加参数</el-button
        >
        <!-- 动态参数的table -->
        <el-table :data="manyTableList" style="width: 100%" border stripe>
          <!-- 扩展列  -->
          <el-table-column type="expand">
            <template slot-scope="{ row }">
              <el-tag
                closable
                @close="handleClose(index, row)"
                v-for="(item, index) in row.attr_vals"
                :key="index"
              >
                {{ item }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >+ New Tag</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="#" type="index" width="50"></el-table-column>
          <el-table-column prop="attr_name" label="参数名称"></el-table-column>
          <el-table-column label="操作" width="320">
            <template slot-scope="{ row }">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="showEditDialog(row)"
                >编辑</el-button
              >

              <el-button type="danger" size="mini" icon="el-icon-delete"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table></el-tab-pane
      >

      <el-tab-pane label="静态属性" name="only"
        ><el-button
          type="primary"
          size="mini"
          :disabled="isBtnDisabled"
          @click="showAddDialog"
          >添加属性</el-button
        ><!-- 动态参数的table -->
        <el-table :data="onlyTableList" style="width: 100%" border stripe>
          <!-- 扩展列  -->
          <el-table-column type="expand">
            <template slot-scope="{ row }">
              <el-tag
                closable
                @close="handleClose(index, row)"
                v-for="(item, index) in row.attr_vals"
                :key="index"
              >
                {{ item }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >+ New Tag</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="#" type="index" width="50"></el-table-column>
          <el-table-column prop="attr_name" label="参数名称"></el-table-column>
          <el-table-column label="操作" width="320">
            <template slot-scope="{ row }">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="showEditDialog(row)"
                >编辑</el-button
              >

              <el-button type="danger" size="mini" icon="el-icon-delete"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'新增' + (activeName === 'many' ? '动态参数' : '静态属性')"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="handleAddDialogClose"
    >
      <!-- 新增表单 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="80px"
      >
        <el-form-item
          :label="activeName === 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
        >
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParam">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="'编辑' + cateTitle"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="handleEditDialogClose"
    >
      <!-- 编辑表单 -->
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item :label="cateTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParam">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      activeName: 'many',
      // 父级分类
      cateList: [],
      // 选中的分类
      // todo:测试语句
      selectedKeys: [1, 3, 6],
      manyTableList: [], // 存动态参数列表
      onlyTableList: [], // 存静态属性列表

      addDialogVisible: false, // 是否显示新增对话框
      addForm: { // 表单数据对象
        attr_name: '', // 名称
        attr_sel: ''
      },

      addRules: { // 表单校验规则对象
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editDialogVisible: false, // 是否显示编辑对话框
      editForm: { // 表单数据对象
        attr_name: '', // 名称
        attr_id: ''// 分类参数 ID
      },
      editRules: { // 表单校验规则对象
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },

  computed: {
    // 判断是否有分类
    isBtnDisabled () {
      return this.selectedKeys.length !== 3
    },
    // 获取分类id
    cateId () {
      return this.selectedKeys[this.selectedKeys.length - 1]
    },
    cateTitle () {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  },

  created () {
    this.getCateList()
    this.getParamList()
  },

  methods: {
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    async handleInputConfirm (row) {
      // const inputValue = this.inputValue
      if (row.inputValue.trim()) {
        row.attr_vals.push(row.inputValue)
        this.saveAttrs(row)
      }
      row.inputValue = ''
      row.inputVisible = false
      await this.$http.put(`categories/${this.cateId}/atstributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
    },
    async saveAttrs (row) {
      await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
    },
    handleClose (index, row) {
      // 删除本地
      row.attr_vals.splice(index, 1)
      // 发请求
      this.saveAttrs(row)
    },
    // 根据 ID 查询参数
    async showEditDialog (row) {
      const { data: res } = await this.$http.get(`categories/${row.cat_id}/attributes/${row.attr_id}`, { params: { attr_sel: row.attr_sel } })
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 关闭对话框事件
    handleEditDialogClose () {
      this.$refs.editFormRef.resetFields()
    },

    // 添加属性或分类
    editParam () {
    // 校验表单
      this.$refs.editFormRef.validate(async isOk => {
        // 如果校验失败，则退出函数
        if (!isOk) return false
        // 如果成功，则发送异步请求
        const { data: resBody } = await this.$http.put(`categories/${this.editForm.cat_id}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.editForm.attr_sel
        })
        // 如果 添加失败，则返回
        if (resBody.meta.status !== 200) return this.$msg.error(resBody.meta.msg)
        // 如果 添加成功，则重新请求渲染列表
        this.getParamList()
        // 关闭窗口
        this.editDialogVisible = false
        // 提示消息
        this.$msg.success(resBody.meta.msg)
      })
    },
    showAddDialog () {
      this.addDialogVisible = true
    },
    handleAddDialogClose () { // 关闭对话框事件
      this.$refs.addFormRef.resetFields()
    },
    addParam () { // 添加属性或分类
    // 校验表单
      this.$refs.addFormRef.validate(async isOk => {
        // 如果校验失败，则退出函数
        if (!isOk) return false
        // 如果成功，则发送异步请求
        const { data: resBody } = await this.$http.post(`categories/${this.cateId}/attributes`, { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
        // 如果 添加失败，则返回
        if (resBody.meta.status !== 201) return this.$msg.error(resBody.meta.msg)
        // 如果 添加成功，则重新请求渲染列表
        this.getParamList()
        // 关闭窗口
        this.addDialogVisible = false
        // 提示消息
        this.$msg.success(resBody.meta.msg)
      })
    },
    handleCascaderChange () {
      if (this.selectedKeys.length < 3) {
        this.selectedKeys = []
        this.manyTableList = []
        this.onlyTableList = []
        return
      }
      this.getParamList()
    },
    async getCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      this.cateList = res.data
      //
    },
    // 获取参数列表
    async getParamList () {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      // 标准写法
      // if (this.activeName === 'many') {
      //   this.manyTableList = res.data
      // } else {
      //   this.onlyTableList = res.data
      // }
      // 简化写法
      this[`${this.activeName}TableList`] = res.data
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
